import OperationDate from './OperationDate.js';
/*************************************************
 * 时间范围选择器
 * 开始时间，截至时间；不必须都要选
 * ***********************************************
 * 在formItem中使用本组件时，切记不要使用$name，否则
 * 会造成组件重复渲染，导致无法正确的回显数据
 *************************************************/
const DateRange = (hook, { DatePicker, Form, moment }) => {
	return {
		name: 'DateRange',
		isJiess: true,
		setup(props, attrs) {
			let { $ref } = hook.$m;
			let {
				startPlaceholder = '开始时间',
					endPlaceholder = '结束时间',
					startDisabled = $ref(null),
					endDisabled = $ref(null),
					format = 'YYYY-MM-DD',
					...param
			} = props;

			let { onChange, value = [] } = attrs.$hookData.frameProps;
			let oper = new OperationDate(hook, moment, value, format);
			this.onUpdated(({ frameProps }) => {
				const v = frameProps.value || [];
				// 根据Form.Item传入value的变化,更新组件,用于回显
				if (JSON.stringify(v) !== JSON.stringify(value)) {
					oper.init((value = v));
				}
			});
			// =====================================================
			const initRender = ({ value, placeholder, ...param }) => {
				return { is: DatePicker, placeholder, style: { flex: 1 }, value, ...param };
			};
			// =====================================================
			const { disabledDates, responseDates, dates } = oper;
			this.add({
				style: { display: 'flex' },
				children: [
					initRender({
						disabledDate: { $proxy: disabledDates[0] },
						value: { $proxy: responseDates[0] },
						disabled: { $proxy: startDisabled },
						placeholder: startPlaceholder,
						onChange(e) {
							oper.changeStart(e);
							// 两个都为假，则提供空数组，用于Form.Item校验
							const result = dates.some((val) => val) ? dates : [];
							if (typeof onChange === 'function') onChange(result);
						},
						...param,
					}),
					// ===================================================
					{ children: '至', style: { padding: '0 4px', lineHeight: '32px' } },
					// ===================================================
					initRender({
						disabledDate: { $proxy: disabledDates[1] },
						value: { $proxy: responseDates[1] },
						disabled: { $proxy: endDisabled },
						placeholder: endPlaceholder,
						onChange(e) {
							oper.changeEnd(e);
							// 两个都为假，则提供空数组，用于Form.Item校验
							const result = dates.some((val) => val) ? dates : [];
							if (typeof onChange === 'function') onChange(result);
						},
						...param,
					})
				]
			});
		},
	};
};
export default DateRange;